package cn.qidd.keep.zuul.config.filter;

import cn.qidd.keep.domain.core.Constants;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Configuration
public class RequestFilter extends ZuulFilter {

    private final Logger logger = LoggerFactory.getLogger(RequestFilter.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public String filterType() {
        return "pre"; // 可以在请求被路由之前调用
    }

    @Override
    public int filterOrder() {
        return 0; // filter执行顺序，通过数字指定 ,优先级为0，数字越大，优先级越低
    }

    @Override
    public boolean shouldFilter() {
        return true;// 是否执行该过滤器，此处为true，说明需要过滤
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        logger.info("RequestFilter {},{}", request.getMethod(), request.getRequestURL().toString());

        String requestURI = request.getRequestURI();

        if (requestURI.contains("api-docs")) {
            logger.info("requestURI:{}, api-docs", requestURI);
            return null;
        }

        if (requestURI.contains("/api/login/login")
                || requestURI.contains("/api/login/devLogin")
                || requestURI.contains("/api/dict/getAllDict")
                || requestURI.startsWith("/service-common/api/file/download")) {
            logger.info("requestURI:{}, token is not must", requestURI);
            return null;
        }

        String token = request.getHeader("X-Header-Token");
        if (StringUtils.isBlank(token)) {
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            ctx.setResponseBody("token is empty");
            logger.info("requestURI:{}, token is empty", requestURI);
            return null;
        }
        Boolean aBoolean = stringRedisTemplate.expire(token, Constants.TOKEN_EXPIRED_TIME, TimeUnit.MINUTES);
        if (aBoolean == null || !aBoolean){
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            ctx.setResponseBody("token is not allowed");
            logger.info("requestURI:{}, token is not allowed", requestURI);
            return null;
        }
        logger.info("requestURI:{}, token is accessed", requestURI);
        return null;
    }
}
